package com.example.patentback.controller;

import cn.hutool.core.map.MapUtil;
import com.example.patentback.entity.PasswordDto;
import com.example.patentback.entity.RegisterDto;
import com.example.patentback.entity.SysRole;
import com.example.patentback.entity.SysUser;
import com.example.patentback.service.SysRoleService;
import com.example.patentback.service.SysUserRoleService;
import com.example.patentback.service.SysUserService;
import com.example.patentback.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/user")
@Api(value = "提供用户相关功能所需的接口", tags = "用户管理")
public class SysUserController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 获取用户信息接口
     *
     * @param principal
     * @return
     */
    @GetMapping("/userInfo")
    public Result userInfo(Principal principal) {
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        return Result.success(MapUtil.builder()
                .put("id", sysUser.getId())
                .put("username", sysUser.getUsername())
                .put("avatar", sysUser.getAvatar())
                .put("created", sysUser.getCreated())
                .map()
        );
    }

    //查询用户信息及角色信息
    @GetMapping("/select/{id}")
    @Transactional
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result selectUser(@PathVariable(name = "id") Long id) {
        SysUser sysUser = sysUserService.selectById(id);
        Assert.notNull(sysUser, "找不到该用户");
        List<Long> roleIds = sysUserRoleService.selectRoleMenuByUserId(id);
        //当新增一个用户时是没有角色的
        if (roleIds.size() > 0) {
            List<SysRole> sysRoles = sysRoleService.selectSysRoleByRoleIds(roleIds);
            sysUser.setSysRoles(sysRoles);
        }
        return Result.success(sysUser);
    }

    //分页查询所有用户或根据用户名分页查询
    @GetMapping("/allUser")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result selectAllUser(String username, int current, int size) {
        List<SysUser> sysUsers = sysUserService.selectByUsername(username, current, size);
        for (SysUser sysUser : sysUsers) {
            List<Long> roleIds = sysUserRoleService.selectRoleMenuByUserId(sysUser.getId());
            if (roleIds.size() > 0) {
                List<SysRole> sysRoles = sysRoleService.selectSysRoleByRoleIds(roleIds);
                sysUser.setSysRoles(sysRoles);
            }
        }
        return Result.success(MapUtil.builder()
                .put("data", sysUsers)
                .put("current", 1)
                .put("size", size)
                .build());

    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result saveUser(@Validated @RequestBody SysUser sysUser) {
        return Result.success(sysUserService.saveSysUser(sysUser));
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result updateUser(@Validated @RequestBody SysUser sysUser) {
        return Result.success(sysUserService.updateUser(sysUser));
    }

    @PostMapping("/delete")
    @Transactional
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result deleteUser(@RequestBody Long[] ids) {
        sysUserService.deleteUser(ids);
        sysUserRoleService.deleteSysUserRoleByUserId(ids);
        return Result.success("删除成功");
    }

    //给用户分配角色
    @PostMapping("/role/{userId}")
    @Transactional
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result rolePerm(@PathVariable(name = "userId") Long userId, @RequestBody Long[] roleIds) {
        sysUserRoleService.updateUserRole(userId, roleIds);
        sysUserService.clearUserAuthorityInfo(userId);
        return Result.success("分配成功");
    }

    @PostMapping("/resetPassword")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public Result resetPassword(@RequestBody Long userId) {
        sysUserService.resetPassword(userId);
        return Result.success("密码重置成功");
    }

    @PostMapping("/updatePassword")
    public Result updatePassword(@Validated @RequestBody PasswordDto passwordDto, Principal principal) {
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        boolean matches = bCryptPasswordEncoder.matches(passwordDto.getOldPassword(), sysUser.getPassword());
        if (!matches) {
            return Result.error("400", "旧密码不正确");
        }
        sysUser.setPassword(bCryptPasswordEncoder.encode(passwordDto.getNewPassword()));
        sysUserService.updateUser(sysUser);
        return Result.success("密码修改成功");
    }

    @PostMapping("/register")
    public Result register(@RequestBody RegisterDto registerDto){
        if (registerDto.getPassword().equals(registerDto.getPassword1())==false){
            return Result.error("100","两次密码输入不一致");
        }else {
            SysUser insert = sysUserService.insert(registerDto);
            if(insert==null){
                return Result.error("100","该用户已被注册！");
            }else {
                return Result.success(insert);
            }
        }
    }
}
